//
//  MyAssetsViewController.m
//  PPDL
//
//  Created by 王洋 on 2019/7/25.
//  Copyright © 2019 王洋. All rights reserved.
//

#import "TTAlipayAuthManager.h"

#import "IncomeListTableViewCell.h"
#import "MyAssetsHeadView.h"

#import "IncomeListTableViewCell.h"

#import "MyAssetsViewController.h"
#import "RechargeViewController.h"
#import "WithdrawViewController.h"

#import "PP_SelWithDrawViewController.h"
#import "WithdrawDetailViewController.h"

@interface MyAssetsViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableview;

@property (nonatomic, strong) NSMutableArray < IncomeListModel *> * dataArray;

@property (nonatomic, strong) MyAssetsHeadView *headView;

@property (nonatomic, strong) MyAssetsHeaderModel *headModel;

@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, assign) NSInteger pageSize;

@property (copy, nonatomic) NSString *outTradeNo;

@end

@implementation MyAssetsViewController


-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"payResultNotification" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payResultCallBack:) name:@"payResultNotification" object:nil];
}

#pragma mark 处理支付回调
-(void)payResultCallBack:(NSNotification *)Noti {
    
    BOOL isPaySuccess = [[Noti.userInfo objectForKey:@"resultStatus"] boolValue];
    NSString *resultMsg = [Noti.userInfo objectForKey:@"memo"];

    [self alert:resultMsg];
    
    if (isPaySuccess) {
        self.headModel.isPreAuth = YES;
        [self.headView fillHeaderWithModel:self.headModel];
        [self request_NotificationAlipayPreAuth];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self initParam];
    [self request_MyAsset];
}

- (void)initParam {
    self.pageNum = 1;
    self.pageSize = 20;
}

- (void)request_MyAsset {
    
    NSDictionary *dic = @{}.mutableCopy;
    [dic setValue:@(self.pageNum) forKey:@"curPage"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_MEMBER_MY_ASSET];
    
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        [[TTNoResultManager shareManager] hideNoResultWithView:self.view];
        [self.tableview.mj_header endRefreshing];
        [self.tableview.mj_footer endRefreshing];
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            
            NSString * code = [data valueForKey:@"code"];
            if ([code isEqualToString:@"200"]) {

                NSDictionary *resultDic = [data valueForKey:@"data"];
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                    
                    double remainder = [[resultDic valueForKey:@"remainder"] doubleValue];//余额
                    double earnestMoney = [[resultDic valueForKey:@"earnestMoney"] doubleValue];//冻结
                    
                    self.headModel.itemTotalMoney = remainder;
                    self.headModel.itemFreezeMoney = earnestMoney;
                    self.headModel.itemWithDrawMoney = remainder - earnestMoney;
                    
                    BOOL isPreAuth = [[resultDic valueForKey:@"authFreeze"] boolValue];
                    self.headModel.isPreAuth = isPreAuth;
                    
                    //收益列表
                    NSArray *tradeRecordRes = [resultDic valueForKey:@"tradeRecordRes"];
                    if (self.pageNum == 1) {
                        [self.dataArray removeAllObjects];
                    }
                    
                    if ( [tradeRecordRes isKindOfClass:[NSArray class]] && tradeRecordRes.count < self.pageSize) {
                        [self.tableview.mj_footer endRefreshingWithNoMoreData];
                    }
                    
                    for (int i = 0; i < tradeRecordRes.count; i++) {
                        
                        NSDictionary *tradeRecordDic = tradeRecordRes[i];
                        IncomeListModel *model = [[IncomeListModel alloc] init];
                        model.itemTitle = [tradeRecordDic valueForKey:@"tradeTitle"];
                        model.relationId  = [tradeRecordDic valueForKey:@"relationId"];
                        NSTimeInterval time = [[tradeRecordDic valueForKey:@"createTime"] doubleValue];
                        model.itemTime = [Utilities getTimeFromTimestamp:time];
                        model.itemIncome = [[tradeRecordDic valueForKey:@"totalFee"] doubleValue];
                        
                        model.relationType = (PPAssetRelationType)[[tradeRecordDic valueForKey:@"relationType"] integerValue];
                        
                        [self.dataArray addObject:model];
                    }
                }
                
            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"msg"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        } else {
            
        }
        
        [self.headView fillHeaderWithModel:self.headModel];
        [self.tableview reloadData];
        

    } FailedBlock:^(NSError * _Nonnull error) {
        
        [self.tableview.mj_header endRefreshing];
        [self.tableview.mj_footer endRefreshing];
        
        WEAKSELF
        [[TTNoResultManager shareManager] showNoResultWithStateInView:self.view errorCode:error.code btnTitle:@"重新加载" didPressButton:^{
            [weakSelf request_MyAsset];
        }];
    }];
}

- (void)chooseRechargeOrPreAuth {
    
    if (self.headModel.isPreAuth) {

        [self alert:@"是否确认取消预授权" leftTitle:@"不取消" Action:^(UIAlertAction * _Nonnull action) {
            
        } rightTitle:@"取消预授权" Action:^(UIAlertAction * _Nonnull action) {
            
            [self request_CancleAlipayPreAuth];
        }];

    } else {

        [self alert:@"请选择去充值或获取支付宝预授权" leftTitle:@"去充值" Action:^(UIAlertAction * _Nonnull action) {

            RechargeViewController *VC = [[RechargeViewController alloc] init];
            [self.navigationController pushViewController:VC animated:YES];

        } rightTitle:@"预授权" Action:^(UIAlertAction * _Nonnull action) {

            [self request_AlipayPreAuth];

        }];
    }
}

- (void)initView {
    
    self.title = @"我的资产";
    self.view.backgroundColor = UIColorHex(0xf1f1f1);
    NSArray *nibView =  [[NSBundle mainBundle] loadNibNamed:@"MyAssetsHeadView"owner:self options:nil];
    self.headView = [nibView objectAtIndex:0];
    WEAKSELF
    self.headView.goWithDraw = ^{
        
        if (weakSelf.infoModel.isRealNameAuth) {
            PP_SelWithDrawViewController *VC = [[PP_SelWithDrawViewController alloc] init];
            VC.model = weakSelf.headModel;
            [weakSelf.navigationController pushViewController:VC animated:YES];
        } else {
            [weakSelf alert:@"请先实名认证"];
        }
        
//        WithdrawViewController *VC = [[WithdrawViewController alloc] init];
//        VC.model = weakSelf.headModel;
//        [weakSelf.navigationController pushViewController:VC animated:YES];

    };
    
    self.headView.goRecharge = ^{
        [weakSelf chooseRechargeOrPreAuth];
    };
    
    self.headView.kequyueAlert = ^{
        [weakSelf alert:@"可取余额 = 账户总额 - 冻结金额"];
    };
    
    self.headView.dongjiejineAlert = ^{
        [weakSelf alert:@"冻结金额产生的原因\n\n1、拍中未付款的商品\n2、有正在参加的拍场"];
    };
    
    [self.tableview registerNib:[UINib nibWithNibName:@"IncomeListTableViewCell" bundle:nil] forCellReuseIdentifier:@"IncomeListTableViewCellID"];

    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableview.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        [weakSelf initParam];
        [weakSelf request_MyAsset];
    }];
    
    self.tableview.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
        weakSelf.pageNum ++;
        [weakSelf request_MyAsset];
    }];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return self.headView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    IncomeListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"IncomeListTableViewCellID" forIndexPath:indexPath];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;

    [cell fillCellWithModel:self.dataArray[indexPath.row]];
    
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.dataArray[indexPath.row].relationType == PPAssetRelationType_BankWithDraw || self.dataArray[indexPath.row].relationType == PPAssetRelationType_WeChatWithDraw || self.dataArray[indexPath.row].relationType == PPAssetRelationType_AliPayWithDraw) {
        
        WithdrawDetailViewController *VC = [[WithdrawDetailViewController alloc] init];
        VC.relationId = self.dataArray[indexPath.row].relationId;
        VC.relationType = self.dataArray[indexPath.row].relationType;
        [self.navigationController pushViewController:VC animated:YES];
    }    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        return 250;
    } else {
        return CGFLOAT_MIN;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return CGFLOAT_MIN;
}

- (MyAssetsHeaderModel *)headModel {
    if (!_headModel) {
        _headModel = [[MyAssetsHeaderModel alloc] init];
    }
    return _headModel;
}

- (NSMutableArray<IncomeListModel *> *)dataArray {
    
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (void)request_AlipayPreAuth {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_PreAuth_ALIPAY];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            
            NSString * code = [data valueForKey:@"code"];
            if ([code isEqualToString:@"200"]) {
                
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                    
                    NSString *orderStr = [resultDic valueForKey:@"body"];
                    
                    NSString *outOrderNo = [resultDic valueForKey:@"outOrderNo"];
                    
                    if (![outOrderNo isKindOfClass:[NSString class]]) {
                        outOrderNo = [NSString stringWithFormat:@"%@",outOrderNo];
                    }
                    
                    self.outTradeNo = outOrderNo;
//                    NSLog(@"请求支付%@",self.outTradeNo);

                    [[TTAlipayAuthManager manager] payWithOrderString:orderStr];
                }
                
            } else {
                
                [self alert:[data valueForKey:@"msg"]];
            }
        } else {
            
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
    
}

- (void)request_CancleAlipayPreAuth {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_PreAuth_ALIPAY_CANCLE];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            
            NSString * code = [data valueForKey:@"code"];
            if ([code isEqualToString:@"200"]) {
                
                self.headModel.isPreAuth = NO;
                [self.headView fillHeaderWithModel:self.headModel];
                [SVProgressHUD showSuccessWithStatus:[data valueForKey:@"msg"]];
                [SVProgressHUD dismissWithDelay:1];
            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"msg"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        } else {
            
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
}

- (void)request_NotificationAlipayPreAuth {
    //预授权成功通知服务器

    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.outTradeNo forKey:@"outOrderNo"];
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_NOTIFICATION_SERVER_PREAUTH];
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            
            NSString * code = [data valueForKey:@"code"];
            if ([code isEqualToString:@"200"]) {
                
            } else {
                [weakSelf request_NotificationAlipayPreAuth];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
}

@end
